__author__ = 'logrus_ak'


import logging
log=logging.getLogger('bishop')

import time
import hashlib,base64


def to_base64(string):
    encoded_base64msg=base64.b64encode(string.encode())
    return str(encoded_base64msg)[2:-1]

def from_base64(b64hex):
    b64hex=b64hex.encode()
    decodemsg=base64.b64decode(b64hex)
    return str(decodemsg)[2:-1].split('!#@#!')

def md5hash_create_salt(string,salt):
    md5hash=hashlib.md5()
    md5hash.update(string.encode())
    md5hash.update(salt.encode())
    string_hash=md5hash.hexdigest()
    return string_hash


def Errorhandler(func):
    """decorator to catch exception with pars"""
    def wrapper(*args,**kwargs):
        count=0
        response=None
        while True:
            try:
                if len(args)==0:
                    response=func()
                    break
                if len(args)>0:
                    response=func(args[0])
                    break
            except Exception as err:
                log.debug('%s' % err)
                count+=1
                if count==5:
                    log.debug('\tStop pars.. urlopen.Error.')
                    break
        return response
    return wrapper


def timedatamake():
    """
    func return MySQL data format
    """
    now=time.gmtime()
    needdata=[now.tm_year, now.tm_mon, now.tm_mday,\
              now.tm_hour, now.tm_min, now.tm_sec]
    count=0
    while len(needdata)>count:
        if len(str(needdata[count]))==1:
            needdata[count]='0'+str(needdata[count])
        count+=1
    needdata=tuple(needdata)
    date="%s-%s-%s %s:%s:%s" %(needdata)
    return date